import paho.mqtt.client as mqtt
import json
import time
import logging
import threading
# import config
import os
import requests
import protocol_parsing
logging.basicConfig(filename='logger.txt', format='%(asctime)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(name=__name__)
# logger.setLevel(level=logging.INFO)
filehandler = logging.FileHandler("log.txt")
filehandler.setLevel(logging.WARNING)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
filehandler.setFormatter(formatter)
console = logging.StreamHandler()  # 日志信息显示在终端terminal
console.setLevel(logging.INFO)
console.setFormatter(formatter)
logger.addHandler(filehandler)
logger.addHandler(console)

# 读取基础配置
dir_path = os.path.dirname(os.path.realpath(__file__))
with open(f'{dir_path}/config.json', 'r', encoding='utf-8') as f:
    config = json.load(f)
HOST0 = config.get('HOST0')
PORT0 = config.get('PORT0')
CLIENTID0 = config.get('CLIENTID0')
USERNAME0 = config.get('USERNAME0')
PASSWD0 = config.get('PASSWD0')
TOPICSub = config.get('TOPICSub')
TOPICPub = config.get('TOPICPub')
data = config.get('data')
REQUEST_URL = config.get('REQUEST_URL')


def on_connect(client, userdata, flags, rc):
    logger.info("Connected with result code "+str(rc))
    client.subscribe(TOPICSub)


def on_message(client, userdata, msg):
    strMsg = str(msg.payload)
    logger.warning(f"receive_msg:  {strMsg}")
    write_str = bytes.hex(msg.payload)
    logger.warning(f"msg_payload:  {write_str}")
    with open('qingping_data.txt', 'a') as f:
        write_content = write_str + '\n'
        f.write(write_content)
    """
    b'CG4/\x00\x11\n\x003.1.3_0092"\x05\x0011001$\x04\x00\x01\x8aEa\x1d\x01\x00\x00\x14\x0c\x00k\x8dEaFB0N%X\xc6\x00\xbd\t'
    """
    try:
        content = protocol_parsing.parsing(write_str)
    except:
        return
    logger.warning(f"parsing_msg: {content}")
    payload = content.get('payload', False)
    if not payload:
        logger.warning(f"no_payload:  {payload}")
        return content
    request_data = False
    for i in payload:
        if i.get('key') == '03':
            request_data = i
    logger.warning(f"request_data:  {request_data}")
    request_data = json.dumps(request_data)
    url = REQUEST_URL
    response = None
    try:
        response = requests.post(url=url, data=request_data)
    except:
        # 未请求成功时，存储数据
        with open('request_data.txt', 'a') as f2:
            a_string = request_data + '\n'
            f2.write(a_string)
        return a_string
    logger.warning(f"request_response:  {response}")
    print(response.status_code)
    if response.status_code != 200:
        with open('request_data.txt', 'a') as f2:
            a_string = request_data + '\n'
            f2.write(a_string)
        return strMsg
    response_date = json.loads(response.content)
    logger.warning(f"msg: {response_date.get('msg')} code: {response_date.get('code')}")
    train(strMsg)
    return strMsg


def on_subscribe(client, userdata, mid, granted_qos):
    logger.info(f"On Subscribed: qos = {granted_qos}  userdata = {userdata}  mid = {mid} client = {client}")


def on_disconnect(client, userdata, rc):
    if rc != 0:
        logger.info(f"Unexpected disconnection {rc}")


def train(Msg):
    logger.info(f'收到mqtt消息 {Msg}')

param = json.dumps(data)
client = mqtt.Client(CLIENTID0)


def mqttSubcribe(Topic):
    # 订阅  取消订阅一个再订阅一个 暂时没有使用
    client.unsubscribe(TOPICSub)
    time.sleep(0.1)
    client.subscribe(Topic, qos=0)


def mqttCommunication():
    client.username_pw_set(USERNAME0, PASSWD0)
    client.on_connect = on_connect
    client.on_message = on_message
    client.on_subscribe = on_subscribe
    client.on_disconnect = on_disconnect
    client.connect(HOST0, PORT0, 60)
    # client.loop_start()
    client.loop_forever()


def main():
    mqttThread = threading.Thread(target=mqttCommunication)
    mqttThread.start()


if __name__ == '__main__':
    main()
